package com.ionehe.group.common.uaa.ex.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
@PropertySource({"classpath:u_db.properties"})
@MapperScan(basePackages = UaaDataSourceConfiguration.PACKAGE, sqlSessionFactoryRef = "uaaSqlSessionFactory")
public class UaaDataSourceConfiguration {

    private static Logger LOGGER = org.slf4j.LoggerFactory.getLogger(UaaDataSourceConfiguration.class);


    /**
     * 精确到 aly(master) 目录，以便跟其他数据源隔离
     */
    static final String PACKAGE = "com.ionehe.group.common.uaa.ex.dao";
    static final String MAPPER_LOCATION = "classpath*:com/ionehe/group/common/uaa/ex/dao/*.xml";


    @Bean(name = "uaaTransactionManager")
    @Primary
    public DataSourceTransactionManager brmTransactionManager() {
        return new DataSourceTransactionManager(uaaExDataSource());
    }

    @Bean(name = "uaaSqlSessionFactory")
    @Primary
    public SqlSessionFactory uaaSqlSessionFactory(@Qualifier("uaaExDataSource") DataSource brmDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(brmDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(UaaDataSourceConfiguration.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    @Value("${uaa.ex.druid.type}")
    private Class<? extends DataSource> dataSourceType;

    @Bean(name = "uaaExDataSource")
    @ConfigurationProperties(prefix = "uaa.ex.druid.jdbc")
    @Primary
    public DataSource uaaExDataSource(){

        return DataSourceBuilder.create().type(dataSourceType).build();
    }
}